package com.bw.mine.login

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.lib_base.base.BaseActivity
import com.bw.mine.R
import com.bw.mine.databinding.ActivityLoginBinding
import com.bw.mine.login.viewmodel.LoginViewModel
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient
import com.therouter.TheRouter
import com.therouter.router.Route
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import kotlin.math.log

@AndroidEntryPoint
@Route(path = "/mine/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel>() {
    private var username: String? = null
    private var password: String? = null
    private var isLoggingIn = false // 防止重复登录

    override fun generatePremission(pageName: String): Array<String> {
        TODO("Not yet implemented")
    }

    override fun setupUI() {
        // 设置窗口背景，防止闪屏
        window.setBackgroundDrawableResource(android.R.color.transparent)
    }

    override fun fetchData() {
        TheRouter.inject(this)
        
        // 恢复保存的用户名和密码
        val savedUsername = SPUtils.getInstance().getString("username", "")
        val savedPassword = SPUtils.getInstance().getString("password", "")
        
        if (savedUsername.isNotEmpty()) {
            binding.phone.setText(savedUsername)
        }
        if (savedPassword.isNotEmpty()) {
            binding.password.setText(savedPassword)
            binding.remember.isChecked = true
        }
        
        binding.login.setOnClickListener {
            if (isLoggingIn) return@setOnClickListener // 防止重复点击
            
            username = binding.phone.text.toString()
            password = binding.password.text.toString()
            
            if (username.isNullOrEmpty() || password.isNullOrEmpty()) {
                ToastUtils.showShort("请输入用户名和密码")
                return@setOnClickListener
            }
            
            isLoggingIn = true
            binding.login.isEnabled = false // 禁用登录按钮
            
            EMClient.getInstance().logout(true)
            EMClient.getInstance().login(username ?: "", password ?: "", object : EMCallBack {
                // 登录成功回调
                override fun onSuccess() {
                    vm.getLogin(password ?: "", username ?: "")
                    Log.d("登录成功", "code:$,erro阿斯顿发斯蒂芬r:$")
                }

                // 登录失败回调，包含错误信息
                override fun onError(code: Int, error: String) {
                    Log.d("登录失败", "code:$code,error:$error")
                    isLoggingIn = false
                    binding.login.isEnabled = true
                    ToastUtils.showShort("登录失败：$error")
                }
            })
        }
        
        binding.goRegister.setOnClickListener {
            TheRouter.build("/mine/RegisterActivity").navigation()
        }
        binding.zw.setOnClickListener {
            TheRouter.build("/mine/FingerprintLoginActivity").navigation()
        }
        binding.zfb.setOnClickListener {
            //TODO("Not yet implemented")
            //集成支付宝
        }
        binding.qq.setOnClickListener {
            //TODO("Not yet implemented")
            //集成QQ
        }
        binding.wx.setOnClickListener {
            //TODO("Not yet implemented")
            //集成微信
        }
    }

    override fun observeData() {
        lifecycleScope.launch {
            vm.loginData.collect {
                if (it != null) {
                    SPUtils.getInstance().put("token", it.token)
                    SPUtils.getInstance().put("roleid", it.roleid)
                    if (binding.remember.isChecked) {
                        SPUtils.getInstance().put("username", username ?: "")
                        SPUtils.getInstance().put("password", password ?: "")
                    } else {
                        // 如果未勾选记住密码，清除保存的密码
                        SPUtils.getInstance().put("password", "")
                    }
                    ToastUtils.showLong("登录成功")
                    TheRouter.build("app/MainActivity").navigation()
                    finish() // 登录成功后关闭当前Activity
                }
                Log.d("灌灌灌灌", "空")
            }
        }
    }

    override fun handleEvent() {
    }

    override fun onDestroy() {
        super.onDestroy()
        // 重置登录状态
        isLoggingIn = false
    }

    override val mLayoutResId: Int
        get() = R.layout.activity_login
}